import React, { Fragment, useEffect, useRef } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import {
    Form,
    Input,
    // Select,
    Button,
    Table,
    // DatePicker,
    // Tabs,
    Card
} from 'antd';
import { QuickForm, utils } from 'vv-frontend-components';
// import cookie from 'js-cookie';
// import { history } from 'umi';
import Locale from '@/utils/locale';
// import QueryPage from '@/components/QueryPage';
// import styles from './index.less';
import { CompanyDepartPlus } from '@/containers';
import DateRange from '@/components/DateRange';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { download } from '@/utils/utils';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { Pagination } from '@/components';

const { locale } = new Locale('attendRecord');

// const { MonthPicker } = DatePicker;
// const { Option } = Select;
// const { TabPane } = Tabs;
const { deepTrim } = utils;

const List = ({ form, attendRecord, loading, dispatch, location, route }) => {
    const { getFieldsValue } = form;
    const {
        query: { id: employeeCode, name, signDate, startTime, endTime }
    } = location;
    const { authCode } = new AuthCode(route.code);
    const { recordPagination: pagination, recordData: data } = attendRecord;

    const initDateValue = () => {
        if (employeeCode) {
            return {
                range: signDate ? [moment(signDate), moment(signDate)] : [moment(startTime), moment(endTime)],
                type: employeeCode ? 'custom' : 'month'
            };
        }
        return {
            range: [moment().startOf('month'), moment()],
            type: employeeCode ? 'custom' : 'month'
        };
    };
    const config = [
        {
            field: 'userName',
            label: '员工',
            config: {
                initialValue: name
            },
            component: <Input placeholder="输入姓名" />
        },
        {
            field: 'date',
            config: {
                initialValue: initDateValue()
            },
            component: (
                <DateRange
                    range
                    dateTypes={[
                        {
                            label: '本周',
                            type: 'week'
                        },
                        {
                            label: '本月',
                            type: 'month'
                        },
                        {
                            label: '本年',
                            type: 'year'
                        }
                    ]}
                />
            )
        }
        // {
        //     component: (
        //         <div>
        //             <Button type="primary" icon="search" htmlType="submit">
        //                 {locale('form.search', false)}
        //             </Button>
        //         </div>
        //     )
        // }
        // {
        //     component: (
        //         <Button type="primary" icon="export" ghost>
        //             {locale('form.export', false)}
        //         </Button>
        //     )
        // }
    ];

    // 如果查看个人记录就不显示
    if (!employeeCode) {
        // console.log(user.departmentId);
        config.unshift({
            field: 'companyDepart',
            label: '机构',
            component: <CompanyDepartPlus />
        });
    }

    const columns = [
        {
            title: '工号',
            dataIndex: 'userNo',
            key: 'userNo'
        },
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName'
        },
        {
            title: '组织机构',
            dataIndex: 'departmentName',
            key: 'departmentName'
        },
        // {
        //     title: '考勤卡号',
        //     dataIndex: 'employeeId'
        // },
        {
            title: '打卡时间',
            dataIndex: 'attDatetime',
            key: 'attDatetime'
        },
        // {
        //     title: '是否有效',
        //     dataIndex: 'attVerify',
        //     key: 'attVerify'
        // },
        // {
        //     title: '签到/签退',
        //     dataIndex: 'checkType',
        //     key: 'checkType'
        // },
        {
            title: '考勤来源',
            dataIndex: 'deviceName',
            key: 'deviceName'
        }
    ];

    const getParams = () => {
        const { companyDepart = {}, date = { range: [] }, userName } = getFieldsValue();
        const payload = {
            employeeCode,
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            employeeName: userName,
            pageNo: pagination.current,
            pageSize: pagination.pageSize
        };

        if (!employeeCode) {
            payload.companyCode = companyDepart.companyId;
            payload.departmentCode = companyDepart.departmentId;
        }
        return payload;
    };
    const fetchList = () => {
        dispatch(
            deepTrim({
                type: 'attendRecord/fetchRecordList',
                payload: getParams()
            })
        );
    };

    const handleSubmit = async e => {
        e.preventDefault();
        if (attendRecord.recordPagination.current !== 1) {
            await dispatch({
                type: 'attendRecord/save',
                payload: {
                    recordPagination: {
                        ...attendRecord.recordPagination,
                        current: 1
                    }
                }
            });
        } else {
            fetchList();
        }
    };
    const changeCurrent = async newPagination => {
        await dispatch({
            type: 'attendRecord/save',
            payload: {
                recordPagination: {
                    ...attendRecord.recordPagination,
                    ...newPagination
                }
            }
        });
    };
    const handleExport = () => {
        const { pageNo, pageSize, ...other } = getParams();
        download({
            getData: () =>
                dispatch({
                    type: 'attendRecord/fetchAttendExport',
                    payload: deepTrim(other)
                })
        });
    };
    const isFirstRun = useRef(true);

    useEffect(() => {
        fetchList();

        return () => {
            dispatch({
                type: 'attendRecord/save',
                payload: {
                    recordPagination: {
                        ...pagination,
                        current: 1,
                        pageSize: 10
                    }
                }
            });
        };
    }, []);
    // 每当分页数或页数改变时均应该重新请求表格数据
    useEffect(() => {
        // 第一次不运行
        if (isFirstRun.current) {
            isFirstRun.current = false;
            return;
        }
        fetchList();
    }, [pagination.pageSize, pagination.current]);

    return (
        <PageHeaderWrapper>
            <Fragment>
                <Form layout="inline" onSubmit={handleSubmit}>
                    <Card
                        bordered={false}
                        title="检索条件"
                        extra={
                            <Fragment>
                                <Button type="primary" icon="search" htmlType="submit">
                                    {locale('form.search', false)}
                                </Button>
                                <AuthComponent code={authCode('detail:export')}>
                                    <Button
                                        style={{ marginLeft: '5px' }}
                                        onClick={handleExport}
                                        disabled={loading.effects['attendRecord/fetchRecordList']}
                                    >
                                        导出
                                    </Button>
                                </AuthComponent>
                            </Fragment>
                        }
                    >
                        <QuickForm form={form} config={config} />
                    </Card>
                </Form>
                <Card bordered={false} style={{ marginTop: '12px' }}>
                    <Table
                        bordered
                        columns={columns}
                        loading={loading.models.attendRecord}
                        dataSource={data}
                        rowKey="id"
                        onChange={changeCurrent}
                        pagination={false}
                    />
                    <Pagination onChange={changeCurrent} {...pagination} loading={loading.models.attendRecord} />
                </Card>
            </Fragment>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(
    connect(({ attendRecord, loading }) => ({
        attendRecord,
        loading
    }))(Form.create()(List))
);
